#!/usr/bin/env python

"""
Script loader

This class loads a JSON script
after having parsed some "preprocessor" instructions
"""

import sys, os

class ScriptLoader ( object ):
	def __init__ ( self ):
		self.abs_fname = None

	def load ( self, fname ):
		self.res = []

		self.abs_fname = os.path.abspath ( fname )

		if not os.path.isfile ( self.abs_fname ):
			sys.stderr.write ( "FILE: %s does not exist" % self.abs_fname )
			return

		self.basedir = os.path.dirname ( self.abs_fname )
		os.chdir ( self.basedir )

		self._include ( os.path.basename ( self.abs_fname ) )

		return '\n'.join ( self.res )

	def _include ( self, fname ):
		print "--- INCLUDE: %s" % fname
		for line in open ( fname, "r" ):
			line = line.strip ()
			if not line: continue

			if line.startswith ( "#include" ):
				self._include ( line [ 9 : ].strip () )
			elif line [ 0 ] == '#':
				continue
			else:
				self.res.append ( line )
		


		

		
	
